# 多阶段构建 Dockerfile
# 阶段1: 构建前端
FROM node:18-alpine AS frontend-build

# 设置工作目录
WORKDIR /app/frontend

# 复制前端项目文件
COPY mind-ui/package*.json ./

# 安装依赖
RUN npm install --registry=https://registry.npmmirror.com

# 复制前端源码
COPY mind-ui/ ./

# 构建前端项目
RUN npm run build:prod

# 阶段2: 构建后端
FROM maven:3.9.6-openjdk-17-slim AS backend-build

# 设置工作目录
WORKDIR /app/backend

# 复制Maven配置文件
COPY pom.xml ./
COPY mind-admin/pom.xml ./mind-admin/
COPY mind-common/pom.xml ./mind-common/
COPY mind-framework/pom.xml ./mind-framework/
COPY mind-generator/pom.xml ./mind-generator/
COPY mind-quartz/pom.xml ./mind-quartz/
COPY mind-system/pom.xml ./mind-system/
COPY mind-modules/mind-adjust/pom.xml ./mind-modules/mind-adjust/
COPY mind-modules/mind-cache/pom.xml ./mind-modules/mind-cache/
COPY mind-modules/mind-customer/pom.xml ./mind-modules/mind-customer/
COPY mind-modules/mind-invoice/pom.xml ./mind-modules/mind-invoice/
COPY mind-modules/mind-share/pom.xml ./mind-modules/mind-share/

# 下载依赖（利用Docker缓存层）
RUN mvn dependency:go-offline -B

# 复制源码
COPY mind-admin/ ./mind-admin/
COPY mind-common/ ./mind-common/
COPY mind-framework/ ./mind-framework/
COPY mind-generator/ ./mind-generator/
COPY mind-quartz/ ./mind-quartz/
COPY mind-system/ ./mind-system/
COPY mind-modules/ ./mind-modules/

# 从前端构建阶段复制构建结果到后端静态资源目录
COPY --from=frontend-build /app/frontend/dist/ ./mind-admin/src/main/resources/static/

# 构建后端项目
RUN mvn clean package -DskipTests -B

# 阶段3: 运行时镜像
FROM openjdk:17-jre-slim

# 设置时区
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && echo 'Asia/Shanghai' > /etc/timezone

# 创建应用目录
WORKDIR /app

# 创建非root用户
RUN groupadd -r appuser && useradd -r -g appuser appuser

# 从构建阶段复制jar文件
COPY --from=backend-build /app/backend/mind-admin/target/*.jar app.jar

# 创建日志目录
RUN mkdir -p /app/logs && chown -R appuser:appuser /app

# 切换到非root用户
USER appuser

# 暴露端口
EXPOSE 8080

# 设置JVM参数
ENV JAVA_OPTS="-Xms512m -Xmx1024m -Djava.security.egd=file:/dev/./urandom"

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:8080/actuator/health || exit 1

# 启动应用
CMD ["sh", "-c", "java $JAVA_OPTS -jar app.jar"]